//
// Created by Eric Yu on 27/6/2016.
// Copyright (c) 2016 XO Group. All rights reserved.
//

import UIKit

extension UIImage {
    /**
     image优化大小
     
     - parameter size:    改变后的大小
     - parameter quality: 保真度
     - parameter aspect:  方向
     
     - returns: 优化后的data
     */
    func resizedImageData(size: CGSize, quality: CGFloat, aspect: Bool = true) -> NSData {
        var scaledImageRect = CGRect.zero
        var width: CGFloat = 0.0
        var height: CGFloat = 0.0
        var aspectRatio: CGFloat = 1
        
        if aspect {
            width = size.width / self.size.width;
            height = size.height / self.size.height
            aspectRatio = min(width, height)
            
            scaledImageRect.size.width = self.size.width * aspectRatio
            scaledImageRect.size.height = self.size.height * aspectRatio
        } else {
            scaledImageRect.size.width = size.width
            scaledImageRect.size.height = size.height
        }
        
        UIGraphicsBeginImageContext(scaledImageRect.size)
        self.drawInRect(scaledImageRect)
        let imageContext = UIGraphicsGetImageFromCurrentImageContext()
        let imageData = UIImageJPEGRepresentation(imageContext, quality)
        UIGraphicsEndImageContext()
        
        return imageData!
    }
}
